package cn.edu.cqu.ssodemo;

import cn.edu.cqu.ssodemo.Token.Token;
import cn.edu.cqu.ssodemo.Token.TokenRepository;
import cn.edu.cqu.ssodemo.User.User;
import cn.edu.cqu.ssodemo.User.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Optional;

@Controller
public class Login {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private TokenRepository tokenRepository;
    private String back;

    @RequestMapping(value = "/back")
    public void getBack(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        back = request.getParameter("back");
        HttpSession session = request.getSession();
        String id = session.getId();
        System.out.println(id);
        login(request, response);
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        String id = session.getId();
        Optional<Token> token_Optional = tokenRepository.findById(id);

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if (username == null) {
            if (!token_Optional.isPresent()) {
                request.getRequestDispatcher("/toPage/login").forward(request, response);
                return null;
            } else {
                response.sendRedirect(back + "?msg=true");
                return null;
            }
        }
        Optional<User> user_Optional = userRepository.findById(username);
        if (!user_Optional.isPresent())
            return "register";
        User user = user_Optional.get();
        if (!user.getPassword().equals(password))
            return "wrongPassword";
        else {
            Token token = new Token();
            token.setId(session.getId());
            token.setName("token_" + session.getId());
            session.setAttribute("token", token);
            tokenRepository.insert(token);
            response.sendRedirect("/toPage/success" + "?msg=true");
            return null;
        }
    }
}